package cn.ava.ymcc.mq.listener;

import cn.ava.ymcc.constants.CommonConstants;
import cn.ava.ymcc.domain.PayOrder;
import cn.ava.ymcc.dto.PayNotifyDto;
import cn.ava.ymcc.service.IPayOrderService;
import com.alibaba.fastjson.JSONObject;
import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;


@RocketMQTransactionListener(txProducerGroup = "tx-alipay-group")
public class OrderPayNotifyTransListener implements RocketMQLocalTransactionListener{

    @Autowired
    private IPayOrderService payOrderService;


    /**
     * 本地事务执行
     * @param msg
     * @param arg
     * @return
     */
    @Override
    public RocketMQLocalTransactionState executeLocalTransaction(Message msg, Object arg) {
        // 非空校验
        if (arg == null) {
            return RocketMQLocalTransactionState.ROLLBACK; // 数据为空直接失败回滚
        }
        try {
            Map<String,Object> map = (HashMap<String,Object>)arg;
            payOrderService.handlerPayNotify(map);
            return RocketMQLocalTransactionState.COMMIT; // 本地事务执行成功
        } catch (Exception e) {
            e.printStackTrace();
            return RocketMQLocalTransactionState.ROLLBACK; // 报错
        }
    }

    /**
     * 回调检查
     * @param msg
     * @return
     */
    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message msg) {
        byte[] payload = (byte[]) msg.getPayload();
        String jsonObj = new String(payload, StandardCharsets.UTF_8);
        try {
            // 转为对象
            PayNotifyDto payNotifyDto = JSONObject.parseObject(jsonObj, PayNotifyDto.class);
            // 校验本地事务是否执行成功,订单是否保存
            PayOrder payOrder = payOrderService.checkPayOrder(payNotifyDto.getOrderNo());
            if (payOrder == null || CommonConstants.OrderPayState.STATE_SUCCESS.equals(payOrder.getPayStatus())) {
                // 支付单为空,或状态不是已完成支付直接回滚
                return RocketMQLocalTransactionState.ROLLBACK;
            }
            return RocketMQLocalTransactionState.COMMIT;
        } catch (Exception e) {
            e.printStackTrace();
            return RocketMQLocalTransactionState.UNKNOWN;
        }
    }
}
